<template>
  <view>
   <view class="navbar">
     <uni-nav-bar @clickLeft="goback" leftIcon="left" fixed="true" border="false" color="#FFF" statusBar="true"
       backgroundColor="#22b9a3" title="单元测试预览" />
   </view>
  </view>
</template>

<script setup>
  import {
    ref
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import * as http from '@/utils/http'
  const pdfUrl = ref()
  onLoad(async (option) => {

    const resourceId = option.resourceId
    //获取单个资源
    const result = await http.getRequest("/xhyy/exam/get", {
      id: resourceId
    })
    if (result.code == 0) {
      pdfUrl.value =decodeURIComponent(result.data.examUrl)
      previewPDFInWeChat(pdfUrl.value,result.data.examName)
    } else {
      uni.showToast({
        title: '获取资源失败',
        icon: 'error',
        duration: 1000
      })
    }
  })
  
  // 在需要预览的地方调用此方法
  function previewPDFInWeChat(pdfUrl, fileName) {
    uni.showLoading({
      title: '加载PDF中...',
      mask: true
    });
  
    // 第一步：下载文件
    uni.downloadFile({
      url: pdfUrl,
      success: (downloadRes) => {
        uni.hideLoading();
        
        if (downloadRes.statusCode === 200) {
          // 第二步：打开文档
          wx.openDocument({
            filePath: downloadRes.tempFilePath,
            fileType: 'pdf',
            showMenu: true, // 显示右上角菜单（转发、收藏等）
            success: (openRes) => {
              console.log('PDF打开成功');
              
              // 可选：文件缓存处理
              cacheFile(downloadRes.tempFilePath, fileName);
            },
            fail: (openErr) => {
              console.error('PDF打开失败:', openErr);
              uni.showToast({
                title: '打开PDF失败',
                icon: 'none'
              });
            }
          });
        } else {
          throw new Error(`下载失败，状态码：${downloadRes.statusCode}`);
        }
      },
      fail: (downloadErr) => {
        uni.hideLoading();
        console.error('PDF下载失败:', downloadErr);
        uni.showToast({
          title: '下载PDF失败',
          icon: 'none'
        });
      }
    });
  }
  
  // 文件缓存功能（可选）
  function cacheFile(tempFilePath, fileName) {
    try {
      const fileManager = wx.getFileSystemManager();
      const cachedPath = `${wx.env.USER_DATA_PATH}/${fileName}`;
      
      fileManager.saveFile({
        tempFilePath: tempFilePath,
        filePath: cachedPath,
        success: (res) => {
          console.log('文件缓存成功:', res.savedFilePath);
        },
        fail: (err) => {
          console.warn('文件缓存失败:', err);
        }
      });
    } catch (e) {
      console.warn('缓存处理异常:', e);
    }
  }
  function goback() {
    uni.navigateBack()
  }
</script>

<style lang="scss" scoped>
  .navbar ::v-deep .uni-nav-bar-text {
    font-size: $uni-font-size-title !important;
    font-family: "siyuan";
  }
</style>